﻿
Imports System.Data.SqlClient
''' <summary>
''' 成品拆分
''' </summary>
''' <remarks>songrenhua 2009-06-09</remarks>
Public Class Frm_MauFProductSplit
    Implements IDServer.IDServer.IDServer
    Private WithEvents MainForm As Frm_MainForm
    Private fLoadBool As Boolean = False
    Private ActionHelp As IDServer.IDServer.ActionBtn = IDServer.IDServer.ActionBtn.ActionHelp
    Private DS As DataSet

    Public Property SelectObject() As Frm_MainForm
        Get
            Return MainForm
        End Get
        Set(ByVal value As Frm_MainForm)
            MainForm = value
        End Set
    End Property

    ''' <summary>
    ''' 設置按鈕狀態
    ''' </summary>
    ''' <param name="type">操作類型</param>
    ''' <param name="IsFind">是否是流覽</param>
    ''' <remarks></remarks>
    Private Sub SetButton(ByVal type As ButtonType, ByVal IsFind As Boolean)
        Try

            Dim BillStatus As String = ""

            If Not Me.DVG_Master.CurrentRow Is Nothing Then
                BillStatus = Me.DVG_Master.CurrentRow.Cells("BillStatus").Value
            End If

            Select Case type
                Case ButtonType.Add
                    With MainForm
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = False
                        .ToolStripImport.Enabled = False
                        .ToolStripPrint.Enabled = False
                        .ToolStripFilter.Enabled = False
                    End With

                Case ButtonType.Browse
                    With MainForm
                        .ToolStripAdd.Enabled = True
                        .ToolStripEdit.Enabled = IsFind AndAlso (BillStatus = E_VouStatus.保存.ToString OrElse BillStatus = E_VouStatus.反核准.ToString)
                        .ToolStripDelete.Enabled = IsFind AndAlso (BillStatus = E_VouStatus.保存.ToString OrElse BillStatus = E_VouStatus.反核准.ToString)
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = False
                        .ToolStripImport.Enabled = False
                        .ToolStripPrint.Enabled = False
                        .ToolStripFilter.Enabled = False
                        .ToolStripCheck.Enabled = (BillStatus = E_VouStatus.保存.ToString OrElse BillStatus = E_VouStatus.反核准.ToString)
                        .ToolStripComplete.Enabled = False
                        .ToolStripUnCheck.Enabled = (BillStatus = E_VouStatus.核准.ToString)
                    End With

                Case ButtonType.Cancel
                    With MainForm
                        .ToolStripAdd.Enabled = True
                        .ToolStripEdit.Enabled = IsFind
                        .ToolStripDelete.Enabled = IsFind
                        .ToolStripSave.Enabled = False
                        .ToolStripCancel.Enabled = False
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = False
                        .ToolStripImport.Enabled = False
                        .ToolStripPrint.Enabled = False
                        .ToolStripFilter.Enabled = False

                    End With

                Case ButtonType.Edit
                    With MainForm
                        .ToolStripAdd.Enabled = False
                        .ToolStripEdit.Enabled = False
                        .ToolStripDelete.Enabled = False
                        .ToolStripSave.Enabled = True
                        .ToolStripCancel.Enabled = True
                        .ToolStripFirst.Enabled = False
                        .ToolStripLast.Enabled = False
                        .ToolStripNext.Enabled = False
                        .ToolStripPrivous.Enabled = False
                        .ToolStripExport.Enabled = False
                        .ToolStripImport.Enabled = False
                        .ToolStripPrint.Enabled = False
                        .ToolStripFilter.Enabled = False
                    End With

            End Select
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try

    End Sub
#Region "公用"

    Public Function ActionAdd() As Boolean Implements IDServer.IDServer.IDServer.ActionAdd
        Try
            If AddEnable = False Then
                MessageBox.Show("對不起，您沒有新增權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If
            Me.TabControl1.SelectedIndex = 1
            ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd
            SetButton(ButtonType.Add, False)
            ClearText()
        Catch ex As Exception
        End Try
    End Function

    Public Function ActionCancel() As Boolean Implements IDServer.IDServer.IDServer.ActionCancel
        Try
            SetButton(ButtonType.Browse, True)
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
            TabControl1_Selected(Nothing, Nothing)
        Catch ex As Exception
            MessageBox.Show(ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try

    End Function
    ''' <summary>
    ''' 刪除記錄
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ActionDelete() As Boolean Implements IDServer.IDServer.IDServer.ActionDelete
        Try
            If DS.Tables(0).Rows.Count <= 0 Then
                Exit Function
            End If
            If EditEnable = False Then
                MessageBox.Show("對不起，您沒有刪除權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If
            Dim SplitNum As String
            If Me.TabControl1.SelectedIndex = 0 Then
                SplitNum = Me.DVG_Master.Rows(Me.DVG_Master.CurrentRow.Index).Cells(0).Value.ToString & ""
            ElseIf Me.TabControl1.SelectedIndex = 1 And Me.TxtSplitNum1.Text.Length > 0 Then
                SplitNum = Me.TxtSplitNum1.Text.Trim
            Else
                Exit Function
            End If
            Dim SQL As String
            SQL = "  DELETE FROM STOR_TRADEDETAIL  WHERE  BONUM IN  "
            SQL += " (SELECT BONUM   FROM DBO.STOR_TRADEMASTER WHERE INOROUTTYPE = '09' AND SMNUM = '" & SplitNum & "')  "
            SQL += " DELETE FROM DBO.MAU_FPRODUCTSPLIT  WHERE SPLITNUM = '" & SplitNum & "'"
            SQL += " DELETE FROM STOR_TRADEMASTER WHERE SMNUM = '" & SplitNum & "' AND INOROUTTYPE = '09'"
            Exec(SQL, E_ExecType.ExecuteNonQuery)
            MessageBox.Show("刪除成功", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            '刪除當前的DGV中的記錄
            Dim DT As DataTable = CType(Me.DVG_Master.DataSource, DataTable)
            Dim Drow() As DataRow = DT.Select("SplitNum= '" & SplitNum & "'")
            For Each row As DataRow In Drow
                row.Delete()
            Next
            DT.AcceptChanges()
            Me.DVG_Master.DataSource = DT
            SetDataGridViewBackColor(Me.DVG_Master, "BillStatus")
        Catch ex As Exception
            MessageBox.Show(ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Function

    Public Function ActionEdit() As Boolean Implements IDServer.IDServer.IDServer.ActionEdit
        Try
            If EditEnable = False Then
                MessageBox.Show("對不起，您沒有修改權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If
            If DS.Tables(0).Rows.Count <= 0 Then
                Exit Function
            End If
            If Me.TabControl1.SelectedIndex = 0 Then
                Me.TabControl1.SelectedIndex = 1
            End If
            ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit
            SetButton(ButtonType.Edit, False)
            Me.GroupBox3.Enabled = True
            Me.DGV_Detail.ReadOnly = False
        Catch ex As Exception
            MessageBox.Show(ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Function

    Public Function ActionExport() As Boolean Implements IDServer.IDServer.IDServer.ActionExport

    End Function

    Public Function ActionFilter() As Boolean Implements IDServer.IDServer.IDServer.ActionFilter

    End Function

    Public Function ActionGoFirst() As Boolean Implements IDServer.IDServer.IDServer.ActionGoFirst

    End Function

    Public Function ActionGoLast() As Boolean Implements IDServer.IDServer.IDServer.ActionGoLast

    End Function

    Public Function ActionGoNext() As Boolean Implements IDServer.IDServer.IDServer.ActionGoNext

    End Function

    Public Function ActionGoPrevious() As Boolean Implements IDServer.IDServer.IDServer.ActionGoPrevious

    End Function

    Public Function ActionImport() As Boolean Implements IDServer.IDServer.IDServer.ActionImport

    End Function

    Public Function ActionInitialize() As Boolean Implements IDServer.IDServer.IDServer.ActionInitialize

    End Function

    Public Function ActionPrint() As Boolean Implements IDServer.IDServer.IDServer.ActionPrint

    End Function

    Public Function ActionSave() As Boolean Implements IDServer.IDServer.IDServer.ActionSave
        Me.DGV_Detail.Sort(Me.DGV_Detail.Columns("BATCH"), System.ComponentModel.ListSortDirection.Ascending)
        SaveData()
    End Function

    Public Function ActionSelect() As Boolean Implements IDServer.IDServer.IDServer.ActionSelect

    End Function
    ''' <summary>
    ''' 審核過成
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ActionChecked() As Boolean
        Try
            If CheckEnable = False Then
                MessageBox.Show("對不起，您沒有審核權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If
            If Me.DVG_Master.CurrentRow Is Nothing Then Return False
            If MessageBox.Show(My.Resources.ComfirmChecked, Msg.CompanyName, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) <> DialogResult.OK Then Return False
            Dim BoNum As String = Me.DVG_Master.CurrentRow.Cells("SplitNum").Value & ""
            Dim Sql As String = "Update MAU_FPRODUCTSPLIT  set BillStatus='B' Where SplitNum='" & BoNum & "'" & vbCrLf
            Sql &= " update Stor_TradeMaster set BoStatus='B' where Isnull(SmNum,'')='" & BoNum & "' AND INOROUTTYPE = '09'"

            Exec(Sql, E_ExecType.ExecuteNonQuery)
            Dim Dtab As DataTable = DirectCast(Me.DVG_Master.DataSource, DataTable)
            Dim DRow() As DataRow = Dtab.Select("SplitNum='" & BoNum & "'")
            If DRow.Length > 0 Then
                DRow(0).Item("BillStatus") = E_VouStatus.核准.ToString
            End If
            Dtab.AcceptChanges()
            Me.SetButton(ButtonType.Browse, True)
            SetDataGridViewBackColor(Me.DVG_Master, "BillStatus")
            MessageBox.Show(My.Resources.CheckSuccess, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Return True
        Catch ex As Exception
            MessageBox.Show("ActionChecked:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

    ''' <summary>
    ''' 反審核
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function ActionUnchecked() As Boolean
        Try
            If UncheckEnable = False Then
                MessageBox.Show("對不起，您沒有反審核權限", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Function
            End If

            If Me.DVG_Master.CurrentRow Is Nothing Then Return False
            If MessageBox.Show(My.resources.ComfirmUnchecked, Msg.CompanyName, MessageBoxButtons.OKCancel, MessageBoxIcon.Question) <> DialogResult.OK Then Return False

            Dim BoNum As String = Me.DVG_Master.CurrentRow.Cells("SplitNum").Value

            Dim Sql As String = "Update Mau_FProductSplit  set BillStatus='C' Where SplitNum='" & BoNum & "'" & vbCrLf
            Sql &= " update Stor_TradeMaster set BoStatus='C' where Isnull(SmNum,'')='" & BoNum & "' AND INOROUTTYPE = '09'" & vbCrLf

            Exec(Sql, E_ExecType.ExecuteNonQuery)
            Dim Dtab As DataTable = DirectCast(Me.DVG_Master.DataSource, DataTable)
            Dim DRow() As DataRow = Dtab.Select("SplitNum='" & BoNum & "'")
            If DRow.Length > 0 Then
                DRow(0).Item("BillStatus") = E_VouStatus.反核准.ToString
            End If
            Dtab.AcceptChanges()
            Me.SetButton(ButtonType.Browse, True)
            SetDataGridViewBackColor(Me.DVG_Master, "BillStatus")
            MessageBox.Show(My.resources.UnCheckSuccess, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Return True
        Catch ex As Exception
            MessageBox.Show("ActionUnchecked:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Function

#End Region
    ''' <summary>
    ''' 查詢要拆分的貨品
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub FindGoods()
        Try
            Dim SQL As String = String.Empty
            Dim DT As DataTable
            SQL = " SELECT TOP(1) REPLACE (ISNULL(BARCODE,''),'*','')AS BARCODE,ISNULL(ENNAME,'')AS ENNAME FROM BSC_GOODS WHERE 1=1 "
            If Me.TxtBarCode.Text.Length > 0 Then
                SQL += " AND REPLACE(BARCODE,'*','') = replace('" & Me.TxtBarCode.Text.Trim & "','*','') "
            End If
            If Me.TxtEnname.Text.Length > 0 Then
                SQL += " and ENNAME = '" & Me.TxtEnname.Text.Trim & "' "
            End If
            DT = Exec(SQL, E_ExecType.DataTable)
            If DT.Rows.Count <= 0 Then
                MessageBox.Show("此貨品不存在,請重新查找！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Me.TxtEnname.Text = ""
                Me.TxtBarCode.Text = ""
                Exit Sub
            End If
            Dim BarCode As String = String.Empty
            Dim Enname As String = String.Empty
            BarCode = DT.Rows(0)(0).ToString
            Enname = DT.Rows(0)(1).ToString
            Me.TxtBarCode.Text = BarCode
            Me.TxtEnname.Text = Enname
        Catch ex As Exception
            MsgBox(ex.Message, Msg.CompanyName, MsgBoxStyle.Information)
        End Try
    End Sub

    Private Sub TxtBarCode_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TxtBarCode.KeyDown, TxtEnname.KeyDown
        Try
            If e.KeyCode = Keys.Enter Then
                FindGoods()
                Me.TxtRemark.Focus()
            End If
        Catch ex As Exception
            MsgBox(ex.Message, Msg.CompanyName, MsgBoxStyle.Information)
        End Try
    End Sub

    ''' <summary>
    ''' 成品拆分成補件
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub BtnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnOK.Click
        Try

            If Me.TxtQty.Text.ToString.Length <= 0 Then
                Exit Sub
            End If

            '1.將成品的BarCode，Enname,數量，庫位等等填充到 DGV_FProduct
            '2.將成品按比例生成的補件信息，數量等填充到DGV_BUJIAN
            '3.保存的時候生成一張拆分單，生成一張出庫單，生成一張入庫單

            '1.添加成品信息
            Dim BarCode As String = Replace(Me.TxtBarCode.Text.Trim.ToString, "*", "")
            Dim ENName As String = Me.TxtEnname.Text.Trim.ToString
            Dim QTY As Integer = CType(Me.TxtQty.Text, Integer)
            If Me.TxtBarCode.Text = "" Then
                MessageBox.Show(" 貨品條碼不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If
            If ENName.ToString.Length <= 0 Then
                MessageBox.Show(" 貨品英文名不能為空", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If
            If QTY > 0 Then
                '1.將成品的BarCode，Enname,數量，庫位等等填充到 DGV_FProduct
                Dim SQL As String = String.Empty
                Dim DS As DataSet
                SQL = " SELECT ISSELECTED = CONVERT(BIT,0),A.STOREHOUSE,REPLACE(A.BARCODE,'*','') AS BARCODE,A.BATCH,A.STOREPLACE,A.GOODSAMOUNT as QTY, '" & QTY & "' as GOODSAMOUNT, " & vbCrLf
                SQL += " B.CODE,B.SUPPERITEM,B.ENNAME,B.CNNAME FROM " & vbCrLf
                SQL += " (SELECT PERIOD,STOREHOUSE,BARCODE,BATCH,STOREPLACE,SUM(GOODSAMOUNT) AS GOODSAMOUNT FROM V_VISUALSTOREQUERY  " & vbCrLf
                SQL += "  GROUP BY STOREHOUSE,PERIOD,BARCODE,BATCH,STOREPLACE) A INNER JOIN BSC_GOODS B ON A.BARCODE=B.BARCODE " & vbCrLf
                SQL += "  LEFT JOIN BSC_STORAGE E ON A.STOREPLACE=E.FSTORAGEID WHERE A.STOREHOUSE='" & PubCompanyCode & "' AND " & vbCrLf
                SQL += " ISNULL(A.GOODSAMOUNT,0.00)>0 AND ISNULL(E.FVIRTUAL,'')<>1 AND ISNULL(E.FBUJIAN,'')<>1 " & vbCrLf
                If Me.TxtEnname.Text.ToString.Trim.Length > 0 Then
                    SQL += " AND ISNULL(B.ENNAME,'')='" & Me.TxtEnname.Text.Trim & "' " & vbCrLf
                End If
                If Me.TxtBarCode.Text.ToString.Trim.Length > 0 Then
                    SQL += " AND ISNULL(A.BARCODE,'')='*" & Me.TxtBarCode.Text.Trim & "*' " & vbCrLf
                End If
                SQL += " ORDER BY BATCH ASC,STOREPLACE ASC ,GOODSAMOUNT ASC ;" & vbCrLf
                '2.將成品按比例生成的補件信息，數量等填充到DGV_BUJIAN
                SQL += " SELECT BARCODE,E.FFULLNAME AS  GOODSTYPE, BILLBARCODE, B.LISTA AS UNIT ,D.COLORCNAME AS COLOR, C.SIZESNAME AS SPEC," & vbCrLf
                SQL += " QTY,QTY*" & QTY & " AS GOODSAMOUNT, DESCRIPTION FROM BSC_BOM A  LEFT JOIN ( select ListCode,ListA  from dbo.BSC_OtherDefineB where itemno = (select Id from BSC_OtherDefineA where itemcode = 'UnitDefin')) B ON " & vbCrLf
                SQL += "  A.UNIT = B.LISTCODE  LEFT JOIN BSC_SIZEDEFINE  C ON A.SPEC = C.SIZECODE LEFT JOIN " & vbCrLf
                SQL += " BSC_COLORDEFINE D ON A.COLOR =D.COLORCODE " & vbCrLf
                SQL += " LEFT JOIN BSC_GOODSTYPE E ON CAST(A.GOODSTYPE AS INT) = E.ID " & vbCrLf
                SQL += " WHERE A.BARCODE = '" & ENName & "' " & vbCrLf

                DS = Exec(SQL, E_ExecType.DataSet)
                Me.DGV_Detail.DataSource = DS.Tables(0)
                If DS.Tables(0).Rows.Count > 0 Then

                    Dim SumCount As Double = DS.Tables(0).Compute("sum(QTY)", "1=1")
                    If QTY <= SumCount Then
                        Me.DGV_BUJIAN.DataSource = DS.Tables(1)
                    Else
                        MessageBox.Show("貨品" & ENName & "庫存數量不足", "加朗系統", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    End If
                Else
                    MessageBox.Show("貨品" & ENName & "沒有庫存", "加朗系統", MessageBoxButtons.OK, MessageBoxIcon.Information)
                End If
            Else
                MessageBox.Show("數量必須大於0", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If

        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly, MsgBoxStyle.Information)
        End Try
    End Sub

    ''' <summary>
    ''' 保存數據
    ''' </summary>
    ''' 1.一條拆分記錄
    ''' 2.一條入庫單，一條出庫單
    ''' 3.入庫單，出庫單明細
    ''' <remarks></remarks>
    Private Sub SaveData()
        Dim SqlCN As SqlClient.SqlConnection
        SqlCN = GetConn()
        Dim SqlTran As SqlClient.SqlTransaction
        Dim SqlCmd As New SqlClient.SqlCommand
        Dim SqlBulk As SqlBulkCopy
        SqlTran = SqlCN.BeginTransaction
        Try
            Dim Sql As String = ""
            ''生成成品拆分單號
            Dim Dtab As DataTable = DirectCast(Me.DGV_Detail.DataSource, DataTable) '所要拆分的成品信息
            Dim DtabBU As DataTable = DirectCast(Me.DGV_BUJIAN.DataSource, DataTable) '所要生成的補件信息

            Dim SRows() As DataRow = Dtab.Select("ISSELECTED= TRUE")
            Dim Sum As Integer = 0
            For X As Int32 = 0 To SRows.Length - 1
                Sum = CType(SRows(X)("GOODSAMOUNT"), Integer)
            Next
            If Sum <> CType(Me.TxtQty.Text, Integer) Then
                MessageBox.Show("選中的成品數量與實際數量不相等", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If

            If DtabBU.Rows.Count <= 0 Then
                MessageBox.Show("此貨品的補件不存在", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If

            Dim TextValue As New System.Text.StringBuilder
            Dim TextValueDtl As New System.Text.StringBuilder

            Dim BoNum As String = ""
            Dim MoveDate As Date = Format(Me.DateTimePicker3.Value, "yyyy-MM-dd")
            Dim Remark As String = Me.TxtRemark.Text.Trim
            Dim OperatePerson As String = PubUserName
            Dim OperateDate As Date = Format(Me.DateTimePicker3.Value, "yyyy-MM-dd")
            Dim OPerateComputer As String = My.Computer.Name
            Dim SmNum As String = ""
            Dim Remark2 As String = ""

            Dim BoNumA As String = "" ''出庫
            Dim BoNumB As String = "" ''入庫

            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then

                BoNum = GetValue("EXEC ReturnBillNum 'Mau_FProductSplit','SplitNum','S" & PubCompanyCode & "'")
                SmNum = BoNum
                Me.TxtSplitNum1.Text = BoNum
                Sql &= " Insert Into Mau_FProductSplit(SplitNum, SplitDate,  Remark,  OperatePsn, OperateDate, OperateComputer,BillStatus)" & vbCrLf
                Sql &= " values('" & BoNum & "','" & MoveDate & "','" & Remark & "','" & OperatePerson & "',Getdate(),'" & OPerateComputer & "','A')" & vbCrLf

                Sql &= " Update Number set Number=" & Val(BoNum.Replace("PS", "00")) & " where BillType='SplitNum' " & vbCrLf
                Sql &= "  " & vbCrLf

                BoNumA = AutoCreateBoNum(PubCompanyCode, "-", PubCompanyCode, "Stor_TradeMaster")
                BoNumB = AutoCreateBoNum(PubCompanyCode, "+", PubCompanyCode, "Stor_TradeMaster")

            Else

                BoNum = Me.TxtSplitNum1.Text.Trim & ""
                SmNum = BoNum

                Dim BoNumDtab As New DataTable

                Dim Tsql As String = ""

                Tsql = " select Max(Case TradeType When '-' Then BoNum End) as BoNumA," & vbCrLf
                Tsql &= "       Max(Case TradeType When '+' Then BoNum End) as BoNumB  from  Stor_TradeMaster where Isnull(SmNum,'')='" & SmNum & "'" & vbCrLf

                BoNumDtab = Exec(Tsql, E_ExecType.DataTable)

                If BoNumDtab.Rows.Count > 0 Then
                    BoNumA = BoNumDtab.Rows(0).Item("BoNumA") & ""
                    BoNumB = BoNumDtab.Rows(0).Item("BoNumB") & ""
                End If

                Sql &= " Update Mau_FProductSplit set SplitDate='" & MoveDate & "' ,Remark='" & Remark & "',UpdatePerson='" & OperatePerson & "',UpdateDate=Getdate(),UpdateComputer='" & OPerateComputer & "'"
                Sql &= " where Isnull(SplitNum,'')='" & BoNum & "'"


            End If

            Dim I As Integer = 1
            Dim ISSELECTEDRows() As DataRow = Dtab.Select("ISSELECTED= TRUE")
            For M As Int32 = 0 To ISSELECTEDRows.Length - 1
                Dim TextKey As String = ""
                ''插入到Stor_TradeMaster
                Dim Batch As String = ISSELECTEDRows(M)("Batch").ToString()
                Dim ToStore As String = ISSELECTEDRows(M)("STOREHOUSE").ToString()
                Dim FromStore As String = ISSELECTEDRows(M)("STOREHOUSE").ToString()
                Dim StoreFromPlace As String = ISSELECTEDRows(M)("STOREPLACE").ToString()
                Dim StoreToPlace As String = ISSELECTEDRows(M)("STOREPLACE").ToString()
                Dim GoodsBarCode As String = "*" & ISSELECTEDRows(M)("BARCODE").ToString() & "*"
                Dim Goodsstatus As String = 1
                Dim Goodsamount As Double = ISSELECTEDRows(M)("GOODSAMOUNT").ToString()
                Dim GoodsPrice As Double = 0.0
                Dim GoodsMoney As Double = 0.0
                Dim GoodsOther As String = ""
                Dim Remark_Store As String = ""

                ''[-]操作
                If I = 1 Then
                    Remark_Store = "由庫位調整自動生成出庫單，對應的入庫單為[" & BoNumB & "] ，不要手動修改/刪除。"
                    TextKey &= " Insert Into Stor_TradeMaster(BoNum,SmNum,TradeType,InOrOutType,FromStore,BoStatus,Remark,OperatePerson,OperateDate,OperateComputer,CheckPerson,CheckDate,CheckComputer,DeliverDate)" & vbCrLf
                    TextKey &= " values('" & BoNumA & "','" & SmNum & "','-','09','" & FromStore & "','A','" & Remark_Store & "','" & OperatePerson & "',Getdate(),'" & OPerateComputer & "','" & OperatePerson & "','" & OperateDate & "','" & OPerateComputer & "',Convert(varchar(10),Getdate(),21))" & vbCrLf

                End If
                ''插入到Stor_TradeDetail
                TextKey &= " Insert Into Stor_TradeDetail(BoNum,ItemNo,SmNum,GoodsBarCode,Batch,Goodsstatus,Storeplace,Goodsamount,GoodsPrice,GoodsMoney,GoodsOther)" & vbCrLf
                TextKey &= " values('" & BoNumA & "','" & I & "','" & SmNum & "','" & GoodsBarCode & "','" & Batch & "','" & Goodsstatus & "','" & StoreFromPlace & "'," & Goodsamount & "," & GoodsPrice & "," & GoodsMoney & ",'" & GoodsOther & "')" & vbCrLf
                ''更新Number

                TextKey &= "  " & vbCrLf

                ''[+]操作

                If I = 1 Then
                    Remark_Store = "由庫位調整自動生成入庫單，對應的出庫單為[" & BoNumA & "] ，不要手動修改/刪除。"
                    TextKey &= " Insert Into Stor_TradeMaster(BoNum,SmNum,TradeType,InOrOutType,ToStore,BoStatus,Remark,OperatePerson,OperateDate,OperateComputer,CheckPerson,CheckDate,CheckComputer,DeliverDate)" & vbCrLf
                    TextKey &= " values('" & BoNumB & "','" & SmNum & "','+','09','" & ToStore & "','A','" & Remark_Store & "','" & OperatePerson & "',Getdate(),'" & OPerateComputer & "','" & OperatePerson & "','" & OperateDate & "','" & OPerateComputer & "',Convert(varchar(10),Getdate(),21))" & vbCrLf
                End If
                ''插入到Stor_TradeDetail
                If I = 1 Then
                    Dim N = 1
                    For Each row As DataRow In DtabBU.Rows
                        Dim GoodsBarCode1 As String = "*" & row("BILLBARCODE").ToString.Trim & "*"
                        Dim Count As Int32 = row("Goodsamount").ToString.Trim
                        TextKey &= " Insert Into Stor_TradeDetail(BoNum,ItemNo,SmNum,GoodsBarCode,Batch,Goodsstatus,Storeplace,Goodsamount,GoodsPrice,GoodsMoney,GoodsOther)" & vbCrLf
                        TextKey &= " values('" & BoNumB & "','" & N & "','" & SmNum & "','" & GoodsBarCode1 & "','" & Batch & "','" & Goodsstatus & "','" & StoreToPlace & "'," & Count & "," & GoodsPrice & "," & GoodsMoney & ",'" & GoodsOther & "')" & vbCrLf
                        ''更新Number
                        N = N + 1
                    Next
                End If
                TextKey &= "  " & vbCrLf
                I += 1
                TextValue.Append(TextKey)
            Next


            If TextValue.ToString.Trim <> "" Then
                Sql &= TextValue.ToString & vbCrLf
                Remark2 = "自動生成一張出庫單[" & BoNumA & "]，" & vbCrLf
                Remark2 += "自動生成一張入庫單[" & BoNumB & "]。"
                Sql &= "  update Mau_FProductSplit set Remark2='" & Remark2 & "'  where SplitNum='" & BoNum & "'" & vbCrLf
            End If


            '如果是修改，先刪除後插入
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                ''刪除Stor_TradeDetail/Stor_TradeMaster/
                Dim Delsql As String = ""
                Delsql &= " delete Stor_TradeDetail where Isnull(SmNum,'')='" & BoNum & "'" & vbCrLf
                Delsql &= " delete Stor_TradeMaster where Isnull(SmNum,'')='" & BoNum & "'" & vbCrLf
                ''刪除 

                Delsql &= "  " & vbCrLf

                With SqlCmd
                    .CommandType = CommandType.Text
                    .CommandText = Delsql
                    .Connection = SqlCN
                    .Transaction = SqlTran
                    .ExecuteNonQuery()
                End With
            End If

            With SqlCmd
                .CommandType = CommandType.Text
                .CommandText = Sql
                .Connection = SqlCN
                .Transaction = SqlTran
                .ExecuteNonQuery()
            End With
            SqlTran.Commit()
            Me.TxtRemark2.Text = Remark2

            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Then
                MessageBox.Show("新增成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            Else
                MessageBox.Show("修改成功！", Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If

            SetButton(ButtonType.Browse, True)
            Me.GroupBox3.Enabled = False
            Me.DGV_Detail.ReadOnly = True
            ActionHelp = IDServer.IDServer.ActionBtn.ActionHelp
        Catch ex As Exception
            SqlTran.Rollback()
            MsgBox("btnActionSave:" & ex.Message & ex.StackTrace, MsgBoxStyle.Critical And MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub DVG_Master_RowPostPaint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewRowPostPaintEventArgs) Handles DVG_Master.RowPostPaint, DGV_Detail.RowPostPaint, DGV_BUJIAN.RowPostPaint
        Try
            Dim DGView As DataGridView = DirectCast(sender, DataGridView)
            Dim SBrush As New SolidBrush(DGView.RowHeadersDefaultCellStyle.ForeColor)
            e.Graphics.DrawString(Convert.ToString(e.RowIndex + 1, System.Globalization.CultureInfo.CurrentCulture), e.InheritedRowStyle.Font, SBrush, e.RowBounds.Location.X + 20, e.RowBounds.Location.Y + 4)
        Catch ex As Exception
            MessageBox.Show("DGV_Goods_RowPostPaint:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub

    Private Sub BtnFind_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnFind.Click
        FindSplit(True)
    End Sub

    Private Sub FindSplit(ByVal b As Boolean)
        Try
            Dim SQL As String

            SQL = "SELECT SPLITNUM, SPLITDATE, B.LISTA  BILLSTATUS, REMARK, REMARK2, OPERATEPSN, OPERATEDATE, OPERATECOMPUTER, UPDATEDATE, UPDATEPERSON, UPDATECOMPUTER "
            SQL += " FROM  DBO.MAU_FPRODUCTSPLIT A LEFT JOIN "
            SQL += " (SELECT LISTCODE,LISTA  FROM DBO.BSC_OTHERDEFINEB WHERE ITEMNO = (SELECT ID FROM BSC_OTHERDEFINEA WHERE ITEMCODE = 'BILLSTATUSDEFINE')) B "
            SQL += " ON A.BILLSTATUS = B.LISTCODE "
            If b = True Then
                SQL += " where 1=1"
                If Me.TxtSplitNum.Text.Length > 0 Then
                    SQL += " AND splitNum= '" & Me.TxtSplitNum.Text.Trim & "' "
                End If
                If Me.CBBillStatus.Text.Length > 0 Then
                    SQL += " and billstatus = '" & Me.CBBillStatus.SelectedValue & "' "
                End If
                SQL += " AND SPLITDATE BETWEEN '" & Me.DateTimePicker1.Value.ToString("yyyy-MM-dd") & "' AND '" & Me.DateTimePicker2.Value.ToString("yyyy-MM-dd") & "'  "
            Else
                SQL += " where 1<>1"
            End If
            DS = Exec(SQL, E_ExecType.DataSet)
            Me.DVG_Master.DataSource = DS.Tables(0)
            BindDataGridViewCaption(Me.DVG_Master, Me.ReturnCaption(1))
            If b = True Then
                IsFind = FindRecord()
                SetButton(ButtonType.Browse, IsFind)
            End If
            SetDataGridViewBackColor(Me.DVG_Master, "BillStatus")
        Catch ex As Exception
            MessageBox.Show(ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Sub

    Private Sub LodCB()
        Try
            Dim SQL As String
            Dim DT As DataTable
            SQL = " select ListCode,ListA  from dbo.BSC_OtherDefineB where itemno = (select Id from BSC_OtherDefineA where itemcode = 'BillstatusDefine') "
            DT = Exec(SQL, E_ExecType.DataTable)
            Me.CBBillStatus.DataSource = DT
            Me.CBBillStatus.DisplayMember = "ListA"
            Me.CBBillStatus.ValueMember = "ListCode"
        Catch ex As Exception
            MessageBox.Show(ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Sub

    Private Sub Frm_MauFProductSplit_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        LodCB()
        FindSplit(False)
        FillDetail(False)
        FillBUJIAN(False)
        Me.TxtSplitNum1.Enabled = False
        Me.fLoadBool = True
        Me.CBBillStatus.SelectedIndex = -1
    End Sub

    ''' <summary>
    ''' 判斷是否有記錄
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function FindRecord() As Boolean
        If DS Is Nothing Then
            Return False
            Exit Function
        End If

        If Me.DVG_Master.RowCount = 0 Then
            Return False
        Else
            Return True
        End If

    End Function

    Private Function ReturnCaption(ByVal index As Integer) As Hashtable
        Dim Hash As New Hashtable

        Select Case index
            Case 1
                Hash.Add("SPLITNUM", "拆分單號")
                Hash.Add("SPLITDATE", "拆分日期")
                Hash.Add("BILLSTATUS", "狀態")
                Hash.Add("REMARK", "備註")
                Hash.Add("REMARK2", "備註2")
                Hash.Add("OPERATEPSN", "操作員")
                Hash.Add("OPERATEDATE", "操作日期")
                Hash.Add("OPERATECOMPUTER", "操作電腦")
                Hash.Add("UPDATEDATE", "更新日期")
                Hash.Add("UPDATEPERSON", "更新者")
                Hash.Add("UPDATECOMPUTER", "更新電腦")
            Case 2
                Hash.Add("ISSELECTED", "選擇")
                Hash.Add("storehouse", "倉庫")
                Hash.Add("BARCODE", "條碼")
                Hash.Add("BATCH", "批次")
                Hash.Add("STOREPLACE", "庫位")
                Hash.Add("QTY", "庫存數")
                Hash.Add("GOODSAMOUNT", "數量")
                Hash.Add("CODE", "編碼")
                Hash.Add("SUPPERITEM", "供應商")
                Hash.Add("ENNAME", "英文名")
                Hash.Add("CNNAME", "中文名")
            Case 3
                Hash.Add("BARCODE", "貨品條碼")
                Hash.Add("GOODSTYPE", "物料類型")
                Hash.Add("BILLBARCODE", "物料編號")
                Hash.Add("UNIT", "單位")
                Hash.Add("COLOR", "顏色")
                Hash.Add("SPEC", "規格")
                Hash.Add("QTY", "物料比")
                Hash.Add("GOODSAMOUNT", "數量")
                Hash.Add("DESCRIPTION", "物料描述")
        End Select

        Return Hash
    End Function

    Private Sub TabControl1_Selected(ByVal sender As System.Object, ByVal e As System.Windows.Forms.TabControlEventArgs) Handles TabControl1.Selected
        Try
            If ActionHelp = IDServer.IDServer.ActionBtn.ActionAdd Or ActionHelp = IDServer.IDServer.ActionBtn.ActionEdit Then
                Exit Sub
            End If
            If Me.TabControl1.SelectedIndex = 1 Then
                If Me.DVG_Master.SelectedCells.Count > 0 Then
                    Dim SplitNum As String = Me.DVG_Master.Rows(Me.DVG_Master.CurrentRow.Index).Cells(0).Value.ToString
                    FillText(SplitNum)
                    FillDetail(True)
                    FillBUJIAN(True)
                Else
                    If Not DS Is Nothing Then
                        FillText("")
                        FillDetail(False)
                        FillBUJIAN(False)
                    End If
                End If
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Sub

    Private Sub FillText(ByVal SplitNum As String)
        Try
            Dim SQL As String
            Dim DT As DataTable
            Dim QTY As Integer = 0
            SQL = " SELECT DISTINCT SPLITNUM,SPLITDATE,A.REMARK,REMARK2,REPLACE(GOODSBARCODE,'*','') "
            SQL += "  AS GOODSBARCODE,D.ENNAME,GOODSAMOUNT FROM DBO.MAU_FPRODUCTSPLIT A  "
            SQL += "  LEFT JOIN  STOR_TRADEMASTER B "
            SQL += " ON A.SPLITNUM = B.SMNUM LEFT JOIN STOR_TRADEDETAIL C ON B.BONUM  = C.BONUM "
            SQL += " LEFT JOIN BSC_GOODS D ON C.GOODSBARCODE = D.BARCODE  "
            SQL += " WHERE A.SPLITNUM = '" & SplitNum & "' AND TRADETYPE = '-' AND INOROUTTYPE = '09' "
            DT = Exec(SQL, E_ExecType.DataTable)
            For Each row As DataRow In DT.Rows()
                Me.TxtSplitNum1.Text = SplitNum
                Me.DateTimePicker3.Value = row("SPLITDATE")
                Me.TxtBarCode.Text = row("GOODSBARCODE")
                Me.TxtEnname.Text = row("ENNAME")
                Me.TxtRemark.Text = row("REMARK")
                Me.TxtRemark2.Text = row("remark2")
                QTY += row("GOODSAMOUNT")
                Me.TxtQty.Text = QTY
            Next
            Me.GroupBox3.Enabled = False
            Me.DGV_Detail.ReadOnly = True
        Catch ex As Exception
            MessageBox.Show(ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Sub

    Private Sub FillDetail(ByVal B As Boolean)
        Try
            Dim SQL As String
            Dim DT As DataTable
            SQL = " SELECT ISSELECTED = CONVERT(BIT,1), FROMSTORE as storehouse ,REPLACE(GOODSBARCODE,'*','') AS BARCODE,C.BATCH,"
            SQL += " C.STOREPLACE,'' AS QTY,GOODSAMOUNT,CODE,SUPPERITEM,ENNAME,CNNAME "
            SQL += " FROM DBO.MAU_FPRODUCTSPLIT A "
            SQL += " LEFT JOIN  STOR_TRADEMASTER B ON A.SPLITNUM = B.SMNUM "
            SQL += " LEFT JOIN STOR_TRADEDETAIL C ON B.BONUM  = C.BONUM "
            SQL += " LEFT JOIN BSC_GOODS D ON C.GOODSBARCODE = D.BARCODE "
            If B = True Then
                SQL += " WHERE   TRADETYPE = '-' AND INOROUTTYPE = '09'  and A.SPLITNUM = '" & Me.TxtSplitNum1.Text.Trim & "' "
            Else
                SQL += " WHERE 1<>1 "
            End If
            DT = Exec(SQL, E_ExecType.DataTable)
            Me.DGV_Detail.DataSource = DT
            BindDataGridViewCaption(Me.DGV_Detail, Me.ReturnCaption(2))
        Catch ex As Exception
            MessageBox.Show(ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Sub

    Private Sub FillBUJIAN(ByVal B As Boolean)
        Try
            Dim SQL As String
            Dim DT As DataTable
            Dim QTY As Integer = Me.TxtQty.Text
            Dim ENNAME As String = Me.TxtEnname.Text.Trim
            SQL = " SELECT BARCODE,E.FFULLNAME AS  GOODSTYPE, BILLBARCODE, B.LISTA AS UNIT ,D.COLORCNAME AS COLOR, C.SIZESNAME AS SPEC,"
            SQL += "  QTY,QTY*" & QTY & " AS GOODSAMOUNT, DESCRIPTION FROM BSC_BOM A  LEFT JOIN (  SELECT LISTCODE,LISTA  FROM DBO.BSC_OTHERDEFINEB "
            SQL += "  WHERE ITEMNO = (SELECT ID FROM BSC_OTHERDEFINEA WHERE ITEMCODE = 'UNITDEFIN') ) B ON "
            SQL += "  A.UNIT = B.LISTCODE LEFT JOIN BSC_SIZEDEFINE  C ON A.SPEC = C.SIZECODE LEFT JOIN "
            SQL += "  BSC_COLORDEFINE D ON A.COLOR =D.COLORCODE "
            SQL += "  LEFT JOIN BSC_GOODSTYPE E ON CAST(A.GOODSTYPE AS INT) = E.ID "
            If B = True Then
                SQL += "  WHERE A.BARCODE = '" & ENNAME & "' "
            Else
                SQL += " WHERE 1<>1"
            End If
            DT = Exec(SQL, E_ExecType.DataTable)
            Me.DGV_BUJIAN.DataSource = DT
            BindDataGridViewCaption(Me.DGV_BUJIAN, Me.ReturnCaption(3))

        Catch ex As Exception
            MessageBox.Show(ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Sub

    Private Sub DVG_Master_DoubleClick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DVG_Master.DoubleClick
        Try
            If DS.Tables(0) Is Nothing Then
                Exit Sub
            End If
            If Me.TabControl1.SelectedIndex = 0 Then
                Me.TabControl1.SelectedIndex = 1
            End If
        Catch ex As Exception
            MsgBox("DVG_Master_DoubleClick:" + ex.ToString, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly, Msg.CompanyName)
        End Try
    End Sub

    Private Sub ClearText()
        Try
            FillDetail(False)
            FillBUJIAN(False)
            Me.TxtSplitNum1.Text = ""
            Me.DateTimePicker3.Value = Now()
            Me.TxtEnname.Text = ""
            Me.TxtBarCode.Text = ""
            Me.TxtRemark.Text = ""
            Me.TxtRemark2.Text = ""
            Me.TxtQty.Text = 1
            Me.GroupBox3.Enabled = True
            Me.TxtRemark2.Enabled = False
            Me.DGV_Detail.ReadOnly = False
        Catch ex As Exception
            MessageBox.Show(ex.Message, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Information)
        End Try
    End Sub

    Private Sub DVG_Master_CurrentCellChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DVG_Master.CurrentCellChanged
        Try
            If Me.fLoadBool = False OrElse Me.DVG_Master.RowCount <= 0 Then Exit Sub
            Me.SetButton(ButtonType.Browse, True)
            SetDataGridViewBackColor(Me.DVG_Master, "BillStatus")
        Catch ex As Exception
            MessageBox.Show("DVG_Master_CurrentCellChanged:" & ex.Message & ex.StackTrace, Msg.CompanyName, MessageBoxButtons.OK, MessageBoxIcon.Error)
        End Try
    End Sub
End Class
